"""Main entry point for Auto Review tool."""

import argparse
import logging
import sys
from pathlib import Path

from .config import ConfigManager
from .engine import ReviewEngine
from .scheduler import ReviewScheduler


def setup_logging(log_config: dict) -> None:
    """
    Setup logging configuration.

    Args:
        log_config: Logging configuration dictionary
    """
    log_level = log_config.get("level", "INFO")
    log_file = log_config.get("file", "./logs/review.log")
    max_bytes = log_config.get("max_bytes", 10485760)  # 10MB
    backup_count = log_config.get("backup_count", 5)

    # Ensure log directory exists
    Path(log_file).parent.mkdir(parents=True, exist_ok=True)

    # Configure logging
    logging.basicConfig(
        level=getattr(logging, log_level.upper()),
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        handlers=[
            logging.FileHandler(log_file, encoding="utf-8"),
            logging.StreamHandler(sys.stdout),
        ],
    )

    # Configure file rotation if using RotatingFileHandler
    from logging.handlers import RotatingFileHandler

    root_logger = logging.getLogger()
    # Remove existing file handler
    for handler in root_logger.handlers[:]:
        if isinstance(handler, logging.FileHandler):
            root_logger.removeHandler(handler)

    # Add rotating file handler
    file_handler = RotatingFileHandler(log_file, maxBytes=max_bytes, backupCount=backup_count)
    file_handler.setFormatter(
        logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    )
    root_logger.addHandler(file_handler)


def main() -> None:
    """Main entry point."""
    parser = argparse.ArgumentParser(description="Auto Review - Automated code review tool")
    parser.add_argument(
        "--config",
        type=str,
        default="config.yaml",
        help="Path to configuration file (default: config.yaml)",
    )
    parser.add_argument(
        "--mode",
        type=str,
        choices=["once", "schedule"],
        default="once",
        help="Run mode: 'once' for single run, 'schedule' for scheduled runs (default: once)",
    )
    parser.add_argument(
        "--force",
        action="store_true",
        help="Force re-review of PRs that were already reviewed today",
    )
    parser.add_argument(
        "--date",
        type=str,
        default=None,
        help="Review PRs created on specific date (format: YYYY-MM-DD). Default: today",
    )

    args = parser.parse_args()

    try:
        # Load configuration
        config_manager = ConfigManager(args.config)
        config_manager.validate_config()

        # Setup logging
        log_config = config_manager.get_logging_config()
        setup_logging(log_config)

        logger = logging.getLogger(__name__)
        logger.info("Auto Review tool starting...")

        if args.mode == "schedule":
            # Run in scheduler mode
            scheduler = ReviewScheduler(config_manager)
            scheduler.start()
        else:
            # Run once
            review_date = None
            if args.date:
                from datetime import datetime
                try:
                    review_date = datetime.strptime(args.date, "%Y-%m-%d").date()
                    logger.info(f"Reviewing PRs created on: {review_date}")
                except ValueError:
                    print(f"Error: Invalid date format. Please use YYYY-MM-DD format.", file=sys.stderr)
                    sys.exit(1)
            
            review_engine = ReviewEngine(config_manager, force_review=args.force, review_date=review_date)
            results = review_engine.run_review()
            logger.info(f"Review completed. Total PRs reviewed: {len(results)}")

    except FileNotFoundError as e:
        print(f"Error: Configuration file not found: {e}", file=sys.stderr)
        sys.exit(1)
    except ValueError as e:
        print(f"Error: Configuration validation failed: {e}", file=sys.stderr)
        sys.exit(1)
    except KeyboardInterrupt:
        print("\nInterrupted by user", file=sys.stderr)
        sys.exit(0)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        logging.exception("Unexpected error occurred")
        sys.exit(1)


if __name__ == "__main__":
    main()

